package shiro.authc.sys.realm;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import shiro.authc.sys.entity.Permission;
import shiro.authc.sys.entity.User;
import shiro.authc.sys.mapper.PermissionMapper;
import shiro.authc.sys.service.UserService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 李岩峰
 * @date 2017/11/21 15:30
 * @description
 */
public class OauthRealm extends AuthorizingRealm
{

	@Autowired
	private UserService userService;

	@Autowired
	private PermissionMapper permissionMapper;

	/**
	 * 用户授权
	 *
	 * @param principal
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal)
	{
		//获取登录用户信息
		User user = (User)principal.getPrimaryPrincipal();

		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		List<String> list = new ArrayList<>();
		//获取用户权限信息
		List<Permission> permissions = permissionMapper.selectUserPermission(user.getId());
		for (Permission permission : permissions)
		{
			if (StringUtils.isNotBlank(permission.getPermCode()))
			{
				list.add(permission.getPermCode());
			}
		}
		authorizationInfo.addStringPermissions(list);
		return authorizationInfo;
	}

	/**
	 * 用户身份验证，登录时调用
	 *
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
		throws AuthenticationException
	{
		String username = (String)token.getPrincipal();
		User user = userService.getUserByUsername(username);
		if (null == user)
		{
			return null;
		}
		return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
	}
}
